//
//  NSObject+Extension.m
//  
//
//  Created by Amisear on 15/10/9.
//
//

#import "NSObject+Extension.h"
#import "objc/runtime.h"

@implementation NSObject (Extension)

+ (instancetype)ObjectWithDict:(NSDictionary *)dict {
    
    id obj = [[self alloc]init];
    //需要指定的模型内容
    //创建数组 //里面存放需要获得的模型内容key
    NSArray *propertis = [self.class loadPropertis];
    //遍历寻找
    for (NSString *key in propertis) {
        //给obj 设值对应传进来的字典中的对应key的内容
        if (dict[key] != nil) {
            [obj setValue:dict[key] forKeyPath:key];
        }
        
    }
    
    //  [obj setValuesForKeysWithDictionary:dict];
    
    return obj;
}

//动态加载'类'的属性
const char *kPropertiesKey = "kPropertiesKey";

+ (NSArray *)loadPropertis {
    
    NSArray *plist = objc_getAssociatedObject(self, kPropertiesKey);
    if (plist != nil) {
        return plist;
    }
    unsigned int count = 0;
    objc_property_t *list = class_copyPropertyList([self class], &count);
    
    //遍历数组
    NSMutableArray *arrayM =[NSMutableArray arrayWithCapacity:count];
    for (unsigned int i = 0; i < count; ++i) {
        objc_property_t pkj = list[i];
        
        const char *cname = property_getName(pkj);
        
        //添加到数组
        [arrayM addObject:[NSString stringWithUTF8String:cname]];
    }
    
    free(list);
    
    objc_setAssociatedObject(self, kPropertiesKey, arrayM, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    
    return objc_getAssociatedObject(self, kPropertiesKey);
}



@end
